package com.scx.engine;

import java.sql.DatabaseMetaData;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.bson.Document;
//import com.alibaba.fastjson.JSON;
import com.scx.constant.ConvertEnum;
import com.scx.engine.convert.ParseSqlFactory;

public class SqlProcessor {
	/**
	 * 
	 * 获取拦截后的sql。
	 * <p></p>
	 * @return
	 */
	public String analysis(Configuration configuration, BoundSql boundSql) {
		// 获取sql
		String sql = getSql(configuration, boundSql);
		try {
			// 获取数据源信息
			DatabaseMetaData databaseMetaData = configuration.getEnvironment().getDataSource().getConnection().getMetaData();
			String url = databaseMetaData.getURL();
			String dataBaseName = url.substring(url.indexOf("/"), url.indexOf("?"));
//			String params = JSON.toJSONString(boundSql.getParameterObject());
			// 工厂生成
			Document docBean = new ParseSqlFactory().build(databaseMetaData.getDatabaseProductName(), dataBaseName, sql);
//			docBean.append(ConvertEnum.PARAMS.name(), params);
			// 调用文档生成
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sql;
	}
	
	/**
	 * 
	 * 获取sql语句。
	 * <p></p>
	 * @param configuration
	 * @param boundSql
	 * @return
	 */
	private static String getSql(Configuration configuration, BoundSql boundSql) {
		Object parameterObject = boundSql.getParameterObject();
		List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
		// 将所有的sql的空格去除，只保留一个
		String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
		if (parameterMappings.size() > 0 && parameterObject != null) {
			TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
			if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
				sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));
			} else {
				MetaObject metaObject = configuration.newMetaObject(parameterObject);
				for (ParameterMapping parameterMapping : parameterMappings) {
					String propertyName = parameterMapping.getProperty();
					if (metaObject.hasGetter(propertyName)) {
						Object obj = metaObject.getValue(propertyName);
						sql = sql.replaceFirst("\\?", getParameterValue(obj));
					} else if (boundSql.hasAdditionalParameter(propertyName)) {
						Object obj = boundSql.getAdditionalParameter(propertyName);
						sql = sql.replaceFirst("\\?", getParameterValue(obj));
					}
				}
			}
		}
		return sql;
	}
	
	
	/**
	 * 
	 * 获取ibatis参数。
	 * <p></p>
	 * @param obj 参数信息
	 * @return
	 */
	private static String getParameterValue(Object obj) {
		String value = null;
		if (obj instanceof String) {
			value = "'" + obj.toString() + "'";
		} else if (obj instanceof Date) {
			DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
			value = "'" + formatter.format(obj) + "'";
		} else {
			if (obj != null) {
				value = obj.toString();
			} else {
				value = "";
			}
		}
		return value;
	}
}
